package tchk.xyz.lingyuntutorminiprogram.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tchk.xyz.lingyuntutorminiprogram.dto.RoleDTO;
import tchk.xyz.lingyuntutorminiprogram.entity.SysRole;
import tchk.xyz.lingyuntutorminiprogram.entity.SysRolePermission;
import tchk.xyz.lingyuntutorminiprogram.exception.CustomException;
import tchk.xyz.lingyuntutorminiprogram.mapper.SysRoleMapper;
import tchk.xyz.lingyuntutorminiprogram.service.ISysRolePermissionService;
import tchk.xyz.lingyuntutorminiprogram.service.ISysRoleService;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements ISysRoleService {

    @Autowired
    private ISysRolePermissionService sysRolePermissionService;

    @Override
    public RoleDTO getRoleWithPermissions(Long id) {
        // 1. 查询角色基本信息
        SysRole sysRole = this.getById(id);
        RoleDTO roleDTO = new RoleDTO();
        BeanUtils.copyProperties(sysRole, roleDTO);

        // 2. 查询该角色拥有的所有权限ID
        List<SysRolePermission> relations = sysRolePermissionService.list(
                new LambdaQueryWrapper<SysRolePermission>().eq(SysRolePermission::getRoleId, id)
        );
        List<Long> permissionIds = relations.stream()
                .map(SysRolePermission::getPermissionId)
                .collect(Collectors.toList());
        roleDTO.setPermissionIds(permissionIds);

        return roleDTO;
    }

    @Override
    @Transactional
    public void saveRoleWithPermissions(RoleDTO roleDTO) {

        // [新增] 业务校验：检查code是否已存在
        long count = this.count(new LambdaQueryWrapper<SysRole>().eq(SysRole::getCode, roleDTO.getCode()));
        if (count > 0) {
            throw new CustomException("角色编码已存在，请使用其他编码");
        }
        // 1. 保存角色基本信息
        this.save(roleDTO);

        // 2. 保存新的角色权限关联关系
        saveRolePermissionRelations(roleDTO.getId(), roleDTO.getPermissionIds());
    }

    @Override
    @Transactional
    public void updateRoleWithPermissions(RoleDTO roleDTO) {
        // 1. 更新角色基本信息
        this.updateById(roleDTO);

        // 2. 删除该角色旧的所有权限关联
        sysRolePermissionService.remove(new LambdaQueryWrapper<SysRolePermission>().eq(SysRolePermission::getRoleId, roleDTO.getId()));

        // 3. 保存新的角色权限关联关系
        saveRolePermissionRelations(roleDTO.getId(), roleDTO.getPermissionIds());
    }

    @Override
    public List<SysRole> listAll() {
        return this.list();
    }

    /**
     * 私有辅助方法：保存角色-权限关联
     */
    private void saveRolePermissionRelations(Long roleId, List<Long> permissionIds) {
        if (permissionIds != null && !permissionIds.isEmpty()) {
            List<SysRolePermission> relations = permissionIds.stream().map(permissionId -> {
                SysRolePermission relation = new SysRolePermission();
                relation.setRoleId(roleId);
                relation.setPermissionId(permissionId);
                return relation;
            }).collect(Collectors.toList());
            sysRolePermissionService.saveBatch(relations);
        }
    }
}